package rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBElement;

import pizza.admin.dao.OrderDAO;
import pizza.admin.dao.OrderPizzaDAO;
import pizza.admin.dao.PizzaDAO;
import pizza.admin.dao.UserDAO;
import pizza.admin.entity.Order;
import pizza.admin.entity.OrderPizza;
import pizza.admin.entity.Pizza;
import pizza.admin.entity.User;

import model.XmlOrder;
import model.XmlPizza;

/**
 * 
 * @author Radoslav Stoyanov
 *
 */
@Path("/order")
public class OrderRest {
	/**
	 * Method for getting specific order 
	 * @param Integer id
	 * @return XmlOrder
	 */
	@GET
	@Path("get/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	public XmlOrder getOrder(@PathParam("id") Integer id){
		OrderDAO orderDAO = new OrderDAO();
		Order order = orderDAO.getById(id);
		
		XmlOrder xmlorder = new XmlOrder(order);
		return xmlorder;
	}
	
	/**
	 * Method for adding new order
	 * @param JAXBElement<XmlOrder> xmlorderjaxb
	 * @return boolean
	 */
	@PUT
	@Path("add")
	@Consumes(MediaType.APPLICATION_JSON)
	public Boolean addOrder(JAXBElement<XmlOrder> xmlorderjaxb){
		OrderDAO orderDAO = new OrderDAO();
		Order order = new Order();
		
		XmlOrder xmlorder = xmlorderjaxb.getValue();
		
		order.setPhone(xmlorder.getPhone());
		order.setAddress(xmlorder.getAddress());
		order.setDescription(xmlorder.getDescription());
		
		UserDAO userDAO = new UserDAO();
		User user = userDAO.getById(xmlorder.getUser().getId());
		
		order.setUser(user);
		
		orderDAO.add(order);
		
		if(order.getId() == null){
			return false;
		}
		
		OrderPizzaDAO orderPizzaDAO = new OrderPizzaDAO();
		OrderPizza orderPizza = null;
		PizzaDAO pizzaDAO = new PizzaDAO();
		for(XmlPizza xmlpizza : xmlorder.getPizzas()){
			orderPizza = orderPizzaDAO.getByOrderAndPizzaId(xmlpizza.getId(), order.getId());
			if(orderPizza == null){
				orderPizza = new OrderPizza();
				orderPizza.setOrder(order);
				
				Pizza pizza = pizzaDAO.getById(xmlpizza.getId());
				orderPizza.setPizza(pizza);
				
				orderPizza.setCount(1);
			} else {
				orderPizza.setCount(orderPizza.getCount()+1);
			}
		}
		
		orderPizzaDAO.add(orderPizza);
		
		return true;
	}
}
